﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MinhTam.Objects;
using MinhTam.DataAccess.Web;

public partial class BaiViet : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       // Page.Form.Attributes.Add("enctype", "multipart/form-data");
        if (!IsPostBack)
        {
            typeField.Value = Request.QueryString["typeid"];
            keyField.Value = Request.QueryString["keyid"];
            InitTilte();
            InitData();
            txtTrichDoan.config.toolbar = HelpUtil.GetSimpleCKEditorConfig(this);
            string cor=HelpUtil.GetCKEditorUiColorAdmin(this);
            txtTrichDoan.config.uiColor = cor;
            txtNoiDung.config.uiColor = cor;
           
        }
    }
    private void InitTilte()
    {

        DataTable dt = LOAI_BAI_VIET.GetTableFields(string.Format(@"{0}={1}", LOAI_BAI_VIET.cl_LOAI_BAI_VIET_ID, typeField.Value),
            new string[] { },
            LOAI_BAI_VIET.cl_TEN_LOAI);
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTitle.Text = (string.IsNullOrEmpty(keyField.Value) ? "TẠO MỚI " : "SỬA ") + "BÀI VIẾT " + dt.Rows[0][LOAI_BAI_VIET.cl_TEN_LOAI].ToString().ToUpper();
        }
        else
        {
            Response.Redirect(HelpConstEnum.ADMIN_DEFAULT_PAGE);
        }
    }
    private void InitData()
    {
        btnDelete.OnClientClick = "return confirm('Bạn có chắc là muốn xóa bài viết này?')";
        btnDelete2.OnClientClick = btnDelete.OnClientClick;

        string sql = string.Format(@"SELECT bv.BAI_VIET_ID,bv.TEN_BAI_VIET,bv.NOI_DUNG,bv.NGAY_TAO,ISNULL(bv.NOI_BAT,'N') NOI_BAT, bv.NGAY_CAP_NHAT,
            CASE WHEN u.USERS_ID IS NULL THEN bv.NGUOI_TAO_NAME ELSE u.FULL_NAME END NGUOI_TAO_NAME,bv.NGUOI_TAO_EMAIL,
            u1.FULL_NAME NGUOI_CAP_NHAT_NAME, bv.HINH_THUMBNAIL,bv.TRICH_DOAN,bv.NGUOI_TAO_SDT,bv.NGUOI_TAO_DIA_CHI,bv.DUYET,u.USERS_ID, bv.DA_DOC
            FROM BAI_VIET bv
            LEFT JOIN USERS u ON u.USERS_ID = bv.NGUOI_TAO
            LEFT JOIN USERS u1 ON u1.USERS_ID=bv.NGUOI_CAP_NHAT WHERE BV.BAI_VIET_ID={0}", string.IsNullOrEmpty(keyField.Value) ? "-1" : keyField.Value);
        DataTable dt = SQLConnectWeb.GetTable(sql, BAI_VIET.sTableName);
        if (dt != null && dt.Rows.Count > 0)
        {
            btnSave.Text = "Cập nhật";
            btnSave2.Text = "Cập nhật";
            lblNgayCapNhat.Text = dt.Rows[0][BAI_VIET.cl_NGAY_CAP_NHAT].ToString() == "" ? "" : ((DateTime)dt.Rows[0][BAI_VIET.cl_NGAY_CAP_NHAT]).ToString("dd/MM/yyyy HH:mm");
            lblNgayTao.Text = ((DateTime)dt.Rows[0][BAI_VIET.cl_NGAY_TAO]).ToString("dd/MM/yyyy HH:mm");
            lblNguoiTao.Text = dt.Rows[0]["NGUOI_TAO_NAME"].ToString();
            lblNguoiCapNhat.Text = dt.Rows[0]["NGUOI_CAP_NHAT_NAME"].ToString();
            lblDiaChi.Text = dt.Rows[0][BAI_VIET.cl_NGUOI_TAO_DIA_CHI].ToString();
            lblSDT.Text = dt.Rows[0][BAI_VIET.cl_NGUOI_TAO_SDT].ToString();
            lblEmail.Text = dt.Rows[0][BAI_VIET.cl_NGUOI_TAO_EMAIL].ToString();
            txtTieuDe.Text = dt.Rows[0][BAI_VIET.cl_TEN_BAI_VIET].ToString();
            txtNoiDung.Text = dt.Rows[0][BAI_VIET.cl_NOI_DUNG].ToString();
            txtTrichDoan.Text = dt.Rows[0][BAI_VIET.cl_TRICH_DOAN].ToString();
            ckcNoiBat.Checked = dt.Rows[0][BAI_VIET.cl_NOI_BAT].ToString() == "Y";
            ckcDuyet.Checked = dt.Rows[0][BAI_VIET.cl_DUYET].ToString() == "Y";

            if (!string.IsNullOrEmpty(dt.Rows[0][BAI_VIET.cl_HINH_THUMBNAIL].ToString()))
                Image1.ImageUrl = HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER + dt.Rows[0][BAI_VIET.cl_HINH_THUMBNAIL].ToString();

            if (dt.Rows[0]["USERS_ID"].ToString() != "") rowHide.Visible = false;
            if (dt.Rows[0][BAI_VIET.cl_DA_DOC].ToString() != "Y")
            {
                string sqlU = string.Format(@"UPDATE BAI_VIET 
                    SET DA_DOC = 'Y'                       
                    WHERE BAI_VIET_ID={0}", keyField.Value);
                SQLConnectWeb.ExecSQL(sqlU);
            }

        }
        else
        {
            keyField.Value = "";
            lblTitle.Text = lblTitle.Text.Replace("SỬA", "TẠO MỚI");
            lblNgayCapNhat.Text = "";
            lblNgayTao.Text = SQLConnectWeb.GetSystemDatetime().ToString("dd/MM/yyy HH:mm");
            lblNguoiTao.Text = UserLogin.FULL_NAME(this);
            lblNguoiCapNhat.Text = "";
            btnDelete.Visible = false;
            btnDelete2.Visible = false;
            ckcNoiBat.Checked = true;
            ckcDuyet.Checked = true;
        }

    }

    protected void btnSave_Click(object sender, EventArgs e)
    { string imgPath ="";
        if (string.IsNullOrEmpty(keyField.Value))
        {           
            bool ok = false;
            if (ckcNoiBat.Checked)
            {
                string sqlUpdate = string.Format(@"UPDATE BAI_VIET SET NOI_BAT = 'N' WHERE LOAI_BAI_VIET={0}", typeField.Value);
                ok = SQLConnectWeb.ExecSQL(sqlUpdate);
            }
            else ok = true;
            if (ok)
            {
                if (uploadImage.FileName != "")
                {
                    string ext = System.IO.Path.GetExtension(uploadImage.FileName);
                    imgPath = "IMG_" + DateTime.Now.ToString(HelpConstEnum.ADMIN_FILE_DATEFORMAT) + ext;
                    uploadImage.SaveAs(Server.MapPath(HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER + imgPath));
                    Image1.ImageUrl = HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER + imgPath;
                }
                string sql = @"INSERT INTO BAI_VIET(TEN_BAI_VIET,NOI_DUNG,	LOAI_BAI_VIET,	NGUOI_TAO,	NGAY_TAO,NOI_BAT,HINH_THUMBNAIL,TRICH_DOAN,DUYET,DA_DOC) 
                        VALUES( @TEN_BAI_VIET,	@NOI_DUNG,	@LOAI_BAI_VIET, @NGUOI_TAO,	getdate(),	@NOI_BAT,@HINH_THUMBNAIL,@TRICH_DOAN,@DUYET,'Y')";


                ok = SQLConnectWeb.ExecuteNonQuery(sql,
                        "@TEN_BAI_VIET", txtTieuDe.Text,
                        "@NOI_DUNG", txtNoiDung.Text.Replace("'", ""),
                        "@LOAI_BAI_VIET", typeField.Value,
                        "@NGUOI_TAO", UserLogin.USER_ID(this),
                        "@NOI_BAT", (ckcNoiBat.Checked ? "Y" : "N"),
                        "@HINH_THUMBNAIL", imgPath,
                        "@TRICH_DOAN", txtTrichDoan.Text.Replace("'", ""),
                        "@DUYET", (ckcDuyet.Checked ? "Y" : "N")
                      ) > 0;

            }
            if (ok)
            {
                DataTable dt = SQLConnectWeb.GetTable(string.Format(@"select top 1 bai_viet_id from bai_viet where loai_bai_viet={0} order by bai_viet_id desc", typeField.Value));
                if (dt != null && dt.Rows.Count > 0)
                {
                    keyField.Value = dt.Rows[0]["bai_viet_id"].ToString();
                    btnSave.Text = "Cập nhật";
                    btnSave2.Text = "Cập nhật";
                    btnDelete.Visible = true;
                    btnDelete2.Visible = true;
                    lblTitle.Text = lblTitle.Text.Replace("TẠO MỚI", "SỬA");
                }
            }
            else
            {
                HelpControls.ShowMsgBox(this, "Tạo mới bài viết không thành công!");
            }
        }
        else
        {
            bool ok = false;
            if (ckcNoiBat.Checked)
            {
                string sqlUpdate = string.Format(@"UPDATE BAI_VIET SET NOI_BAT = 'N' WHERE LOAI_BAI_VIET={0}", typeField.Value);
                ok = SQLConnectWeb.ExecSQL(sqlUpdate);
            }
            else ok = true;
            if (ok)
            {

                imgPath = System.IO.Path.GetFileName(Image1.ImageUrl);
                if (uploadImage.FileName != "")
                {
                    string ext = System.IO.Path.GetExtension(uploadImage.FileName);
                    imgPath = "IMG_" + DateTime.Now.ToString(HelpConstEnum.ADMIN_FILE_DATEFORMAT) + ext;
                    uploadImage.SaveAs(Server.MapPath(HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER + imgPath));
                                  
                             
                   
                }
              

                string sql = @"UPDATE BAI_VIET
                            SET TEN_BAI_VIET = @TEN_BAI_VIET,
	                            NOI_DUNG = @NOI_DUNG,
	                            NOI_BAT = @NOI_BAT,
	                            NGUOI_CAP_NHAT = @NGUOI_CAP_NHAT,
	                            NGAY_CAP_NHAT = GetDate(),
                                HINH_THUMBNAIL=@HINH_THUMBNAIL,
                                TRICH_DOAN=@TRICH_DOAN,
                                DUYET=@DUYET
                            WHERE BAI_VIET_ID=@BAI_VIET_ID"
                            ;


                ok = SQLConnectWeb.ExecuteNonQuery(sql,
                        "@TEN_BAI_VIET", txtTieuDe.Text,
                        "@NOI_DUNG", txtNoiDung.Text.Replace("'", ""),
                        "@NOI_BAT", (ckcNoiBat.Checked ? "Y" : "N"),
                        "@NGUOI_CAP_NHAT", UserLogin.USER_ID(this),
                        "@BAI_VIET_ID", keyField.Value,
                        "@HINH_THUMBNAIL", imgPath,
                        "@TRICH_DOAN", txtTrichDoan.Text.Replace("'", ""),
                        "@DUYET", (ckcDuyet.Checked ? "Y" : "N")
                      ) > 0;

            }
            if (ok)
            {
                if (imgPath != System.IO.Path.GetFileName(Image1.ImageUrl))
                    HelpUtil.DeleteFile(this, Image1.ImageUrl);
                if (!string.IsNullOrEmpty(imgPath))
                    Image1.ImageUrl = HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER + imgPath;
                lblNgayCapNhat.Text = SQLConnectWeb.GetSystemDatetime().ToString("dd/MM/yyyy HH:mm");
                lblNguoiCapNhat.Text = UserLogin.FULL_NAME(this);              
            }
            else
            {
                HelpControls.ShowMsgBox(this, "Cập nhật bài viết không thành công!");
            }
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect(string.Format("QuanLyBaiViet.aspx?typeid={0}", typeField.Value));
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        string sql = string.Format("delete from {0} where {1}={2}", BAI_VIET.sTableName, BAI_VIET.cl_BAI_VIET_ID, keyField.Value);
        HelpUtil.DeleteFile(this, Image1.ImageUrl);
       
        if (SQLConnectWeb.ExecSQL(sql))
        {
            btnBack_Click(sender, e);
        }
        else
        {
            HelpControls.ShowMsgBox(this, "Xóa bài viết không thành công!");
        }
    }
 
    protected void btnNew_Click(object sender, EventArgs e)
    {
        keyField.Value = "";      
        txtNoiDung.Text="";
        txtTieuDe.Text = "";
        lblNguoiCapNhat.Text="";
        lblNgayCapNhat.Text="";
        btnSave.Text = "Lưu";
        btnSave2.Text = "Lưu";
        btnDelete.Visible = false;
        btnDelete2.Visible = false;
        lblNgayTao.Text = SQLConnectWeb.GetSystemDatetime().ToString("dd/MM/yyy HH:mm");
        lblNguoiTao.Text = UserLogin.FULL_NAME(this);
        txtTieuDe.Focus();
        Image1.ImageUrl = "";
        txtTrichDoan.Text = "";
        lblTitle.Text = lblTitle.Text.Replace("SỬA", "TẠO MỚI");
    }
    protected void uploadImage_Unload(object sender, EventArgs e)
    {
      
    }
    
}
